﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CodeDynamiksEngine;

namespace codedynamiks_mes_baguio
{
    public partial class frmInventorySystem : Form
    {

        public frmInventorySystem()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        private void InitializeForm()
        {
            page = new TabPage[tabMain.TabPages.Count];
            for (int i = 0; i < tabMain.TabPages.Count; i++)
            {
                page[i] = tabMain.TabPages[i];
            }
           
            modeStack.Add(Mode.SEARCH);
            dataMode = Criteria.Item;

            //Apply privileges
            ApplyPrivileges();

            //Event subscription
            Shared_GUIEvents();
            Search_GUIEvents();
            ItemForm_GUIEvents();
            PRForm_GUIEvents();
            AOBForm_GUIEvents();
        }
        //Shared GUI event handlers
        private void Shared_GUIEvents()
        {
            grdSearch.SelectionChanged += new EventHandler(delegate
            {
                if (grdSearch.SelectedRows.Count == 1)
                {
                    edit = grdSearch.SelectedRows[0].Index;
                }
            });
            grdSearch.DoubleClick += new EventHandler(delegate
            {
                if (grdSearch.SelectedRows.Count == 1)
                {
                    edit = grdSearch.SelectedRows[0].Index;

                    switch (dataMode)
                    {
                        case Criteria.Item:
                            Clear(pnlItemForm.Controls);
                            PushMode(Mode.ITEM_UPDATE);
                            ItemLoadChoices();
                            break;
                        case Criteria.PR:
                            Clear(pnlPRForm.Controls);
                            PushMode(Mode.PR_UPDATE);
                            PRLoadData();
                            break;
                    }
                }
            });
        }

        //Item Search and Registration specific handlers
        private void Search_GUIEvents()
        {
           
            txtSearch.KeyPress += new KeyPressEventHandler(delegate(object s, KeyPressEventArgs e)
            {
                if (e.KeyChar == (char)13)
                {
                    prevSrc = txtSearch.Text;
                    PerformSearch();
                }
            });
            
            btnSearch.Click += new EventHandler(delegate
            {
                prevSrc = txtSearch.Text;
                PerformSearch();
            });
        }
        private void Search_FormatGrid()
        {
            foreach (DataGridViewColumn dvc in grdSearch.Columns)
            {
                if (dvc.ValueType == typeof(float))
                {
                    dvc.DefaultCellStyle.Format = "#,#0.00";
                    dvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                }
            }
        }
        private void ItemForm_GUIEvents()
        {
            btnItemRegister.Click += new EventHandler(delegate
            {
                Clear(pnlItemForm.Controls);
                PushMode(Mode.ITEM_INSERT);
                ItemLoadChoices();
            });
            btnItemCancel.Click += new EventHandler(delegate
            {
                Clear(pnlItemForm.Controls);
                PopMode();
                ApplyMode();
            });
            btnItemSave.Click += new EventHandler(delegate
            {
                switch (modeStack[top])
                {
                    case Mode.ITEM_INSERT:
                        ItemInsertRecord();
                        break;
                    case Mode.ITEM_UPDATE:
                        ItemUpdateRecord();
                        break;
                }
            });
        }
        
        //PR Search and Creation specific handlers
        private void PRForm_GUIEvents()
        {
            btnPRCreate.Click += new EventHandler(delegate
            {
                Clear(pnlPRForm.Controls);
                PushMode(Mode.PR_INSERT);
                ApplyMode();
                PRForm_SetRequestor(true); 
                PRInitItems();
            });
            btnPRCancel.Click += new EventHandler(delegate
            {
                Clear(pnlPRForm.Controls);
                PopMode();
                ApplyMode();
            });
            btnPRAddItem.Click += new EventHandler(delegate
            {
                PRForm_GridAdd();
            });
            btnPRSave.Click += new EventHandler(delegate
            {
                switch (modeStack[top])
                {
                    case Mode.PR_INSERT:
                        PRInsertRecord();
                        break;
                    case Mode.PR_UPDATE:
                        PRUpdateRecord();
                        break;
                }
            });
            btnPRRequestor.Click += new EventHandler(delegate
            {
                if(txtPRRequestor.Enabled) 
                    PRForm_SetRequestor(true);
                else
                    PRForm_SetRequestor(false);
            });
            //grdSearch ContextMenu
            mnuGrdSearchOpen.Click += new EventHandler(delegate
            {
                if (grdSearch.SelectedRows.Count == 1)
                {
                    edit = grdSearch.SelectedRows[0].Index;

                    switch (dataMode)
                    {
                        case Criteria.Item:
                            Clear(pnlItemForm.Controls);
                            PushMode(Mode.ITEM_UPDATE);
                            ItemLoadChoices();
                            break;
                        case Criteria.PR:
                            Clear(pnlPRForm.Controls);
                            PushMode(Mode.PR_UPDATE);
                            PRLoadData();
                            break;
                    }
                }
            });
            mnuGrdSearchPush.Click += new EventHandler(delegate
            {
                if (grdSearch.SelectedRows.Count == 1)
                {
                    edit = grdSearch.SelectedRows[0].Index;
                    string prnum="", fuid="", req ="";

                    items.SetActivePage(0);
                    prnum = items.GetValue(edit, "PR No.").ToString();
                    req = items.GetValue(edit, "Requestor").ToString();

                    items.SetActivePage(1);
                    fuid = items.GetValue(edit, "fID").ToString();
                    
                    //PRPush("MAYOR_OFFICE_PR_APPROVAL", "APPROVAL", fuid, prnum, req);
                }
            });
            //grdPRItems ContextMenu
            mnuPRAddItem.Click += new EventHandler(delegate
            {
                PRForm_GridAdd();
            });
            mnuPRRemoveItem.Click += new EventHandler(delegate
            {
                if (grdPRItems.SelectedRows.Count == 1)
                {
                    prItems.Delete(grdPRItems.SelectedRows[0].Index);
                    PRForm_GridTotal();
                }
            });
            mnuPRAdjustItem.Click += new EventHandler(delegate
            {
                PRForm_GridAdjust();
            });

            //OptionMenu
            pnlPROptions.LostFocus += new EventHandler(delegate
            {
                if (!pnlPROptions.ContainsFocus) pnlPROptions.Visible = false;
            });
            btnPROptions.Click += new EventHandler(delegate
            {
                pnlPROptions.Visible = true;
                pnlPROptions.Focus();  
            });
            btnPRApprove.Click += new EventHandler(delegate
            {
                pnlPROptions.Visible = false;
                PRUpdateStatus("APPROVED");
            });
            btnPRDisapprove.Click += new EventHandler(delegate
            {
                pnlPROptions.Visible = false;
                PRUpdateStatus("DENIED");
            });
        }
        private void PRForm_SetRequestor(bool isCurrentUser)
        {
            if (!isCurrentUser)
            {
                txtPRRequestor.Text = "";
                txtPRDesignation.Text = "";
                txtPRRequestor.Enabled = true;
                txtPRDesignation.Enabled = true;
                txtPRMayor.Enabled = true;
                txtPRRequestor.Focus();
                btnPRRequestor.Text = "Current User";
            }
            else
            {
                txtPRRequestor.Text = CurrentUser.NAME;
                txtPRDesignation.Text = CurrentUser.DESIGNATION;
                txtPRMayor.Text = Common.CFG.Read("CURRENT_MAYOR").ToString();
                txtPRRequestor.Enabled = false;
                txtPRDesignation.Enabled = false;
                txtPRMayor.Enabled = false;
                btnPRRequestor.Text = "Another";
            }
        }
        private void PRForm_GridAdd()
        {
            frmInventoryItemDialog itm = new frmInventoryItemDialog();
            DialogResult dlg = itm.ShowDialog();
            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                prItems.Insert(new object[] { itm.StockNumber, itm.Description, itm.Qty, itm.Unit, itm.EstimateCost });
                PRForm_GridTotal();
            }
        }
        private void PRForm_GridAdjust()
        {
            int i = -1;
            if (grdPRItems.SelectedRows.Count == 0) return;
                
            i = grdPRItems.SelectedRows[0].Index;
            frmInventoryItemDialog itm = new frmInventoryItemDialog(prItems.GetValue(i, "Stock Number").ToString(), prItems.GetValue(i, "Description").ToString(),
                prItems.GetValue(i, "Unit").ToString(), float.Parse(prItems.GetValue(i, "Quantity").ToString()), float.Parse(prItems.GetValue(i, "EstimatedCost").ToString())
                );
            DialogResult dlg = itm.ShowDialog();
            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                prItems.Edit(i,
                    new string[]{"Stock Number", "Description", "Unit", "Quantity", "EstimatedCost"},
                    new object[] { itm.StockNumber, itm.Description, itm.Unit, itm.Qty, itm.EstimateCost }
                    );
                PRForm_GridTotal();
            }

        }
        private void PRForm_GridTotal()
        {
            float total = 0f;
            for (int i = 0; i < prItems.GetRecordCount(0); i++)
            {
                total += float.Parse(prItems.GetValue(i, "Subtotal").ToString());
            }
            txtTotal.Text = total.ToString("#,#0.00");
        }
        
        //Abstract of Bids specific handlers
        bool isABClosing = false;
        private void AOBForm_GUIEvents()
        {
            mnuGrdSearchAOB.Click += new EventHandler(delegate
            {
                isABClosing = false;
                Clear(pnlAOBForm.Controls);
                PushMode(Mode.AOB_UPDATE);
                //ApplyMode();
                //ABInitItems();        //This is a working but slow implementation
                ABLoadData();
            });
            btnABClose.Click += new EventHandler(delegate
            {
                isABClosing = true;
                Clear(pnlAOBForm.Controls);
                PopMode();
                ApplyMode();
            });
            btnABAddSupplier.Click += new EventHandler(delegate
            {
                ABSaveData();
            });
            btnABPreview.Click += new EventHandler(delegate
            {
                frmInventoryTableViewer frm = new frmInventoryTableViewer("Abstract of Bids for P.R.#" + txtABPRNum.Text);
                frm.ShowDialog();
            });
            txtABSupplier.SelectedIndexChanged += new EventHandler(delegate
            {
                if (!isABClosing) ABLoadSupplierBid();
            });
        }
        private void AOBForm_FormatGrid()
        {
            if (grdABBids.Rows.Count > 0)
            {
                grdABBids.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
                grdABBids.Columns[0].Frozen = true;
                grdABBids.Columns[0].ReadOnly = true;
                grdABBids.Columns[0].Width = (grdABBids.Width * 50) / 100;

                grdABBids.Columns[1].DefaultCellStyle.Format = "#,#0.00";
                grdABBids.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;
                grdABBids.Columns[1].Width = (grdABBids.Width * 40) / 100;
                grdABBids.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            }
        }

        //Generic GUI operations
        private void PerformSearch()
        {
            if (radSearchItem.Checked)
                dataMode = Criteria.Item;
            else if (radSearchPR.Checked)
                dataMode = Criteria.PR;
            else if (radSearchPO.Checked)
                dataMode = Criteria.PO;
            
            switch (dataMode)
            {
                case Criteria.Item:
                    //Apply grdSearch context menu
                    mnuGrdSearchPush.Visible = false;
                    mnuGrdSearchAOB.Visible = false;
                    ItemSearch();
                    break;
                case Criteria.PR:
                    mnuGrdSearchPush.Visible = true;
                    mnuGrdSearchAOB.Visible = true;
                    PRSearch();
                    break;
                case Criteria.PO:
                    break;
            }
        }
        private void ApplyPrivileges()
        {
            //To Follow
            if (CurrentUser.FindPrivilege("PROPERTY_CUSTODIAN"))
            {
                radSearchItem.Enabled = true;
                radSearchPR.Enabled = true;
                radSearchPO.Enabled = true;
            }
            else if (CurrentUser.FindPrivilege("MAYOR_OFFICE_APPROVAL"))
            {
                radSearchItem.Enabled = false;
                btnPRCreate.Enabled = false;
                radSearchPR.Enabled = true;
                radSearchPO.Enabled = true;
            }
        }
        private void RemoveTab(int index)
        {
            IntPtr handle = tabMain.Handle;
            if (tabMain.TabPages[index] == page[index]) tabMain.TabPages.RemoveAt(index);
        }
        private void RestoreTab(int index)
        {
            IntPtr handle = tabMain.Handle;
            if (index > tabMain.TabPages.Count - 1)
            {
                tabMain.TabPages.Add(page[index]);
            }
            else if (tabMain.TabPages[index] != page[index])
            {
                tabMain.TabPages.Insert(index, page[index]);
            }
        }

        //GUI level stack operations
        private void ApplyMode()
        {

            switch (modeStack[top])
            {
                case Mode.ITEM_INSERT:
                case Mode.ITEM_UPDATE:
                    if (tabMain.TabPages.Count == page.Length)
                    {
                        RemoveTab(3);
                        RemoveTab(2);
                        RemoveTab(0);
                    }
                    btnItemRegister.Enabled = false;
                    pnlItemForm.Enabled = true;
                    tabMain.Enabled = true;
                    pnlWait.Visible = false;
                    break;
                case Mode.ENGINE:
                    tabMain.Enabled = false;
                    pnlWait.Visible = true;
                    break;
                case Mode.SEARCH:
                    if (tabMain.TabPages.Count != page.Length)
                    {
                        RestoreTab(0);
                        RestoreTab(1);
                        RestoreTab(2);
                        RestoreTab(3);
                    }
                    tabMain.SelectedIndex = 0;

                    //Item Form
                    btnItemRegister.Enabled = true;
                    pnlItemForm.Enabled = false;
                    //PR Form
                    btnPRCreate.Enabled = true;
                    btnPROptions.Enabled = false;
                    pnlPRForm.Enabled = false;

                    tabMain.Enabled = true;
                    pnlWait.Visible = false;
                    break;
                case Mode.PR_UPDATE:
                case Mode.PR_INSERT:
                    if (tabMain.TabPages.Count == page.Length)
                    {
                        RemoveTab(3);
                        RemoveTab(1);
                        RemoveTab(0);
                    }
                    btnPRCreate.Enabled = false;
                    pnlPRForm.Enabled = true;
                    btnPROptions.Enabled = true;
                    tabMain.Enabled = true;
                    pnlWait.Visible = false;
                    break;
                case Mode.AOB_UPDATE:
                    if (tabMain.TabPages.Count == page.Length)
                    {
                        RemoveTab(2);
                        RemoveTab(1);
                        RemoveTab(0);
                    }
                    pnlAOBForm.Enabled = true;
                    tabMain.Enabled = true;
                    pnlWait.Visible = false;
                    break;
            }
        }
        private void PushMode(Mode m)
        {
            modeStack.Add(m);
            top = modeStack.Count - 1;
            //ApplyMode();
        }
        private Mode PopMode()
        {
            Mode m = modeStack[top];
            modeStack.RemoveAt(top);
            top = modeStack.Count - 1;
            //ApplyMode();
            return m;
        }
        private void Clear(Control.ControlCollection pg)
        {
            foreach (Control c in pg)
            {
                if (c is TextBox)
                {
                    ((TextBox)c).Text = "";
                }
                else if (c is ComboBox)
                {
                    ((ComboBox)c).SelectedIndex = -1;
                }
                else if (c is NumericUpDown)
                {
                    ((NumericUpDown)c).Value = ((NumericUpDown)c).Minimum;
                }
                else if (c is CheckBox)
                {
                    ((CheckBox)c).Checked = false;
                }
                else if (c is DataGridView)
                {
                    ((DataGridView)c).DataSource = null;
                    ((DataGridView)c).Refresh();
                }
            }
        }
    }
}
